package com.bluexmicro.ota.dfu

import android.bluetooth.BluetoothDevice
import android.content.Context
import com.bluexmicro.bluetooth.BluetoothCentral
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import java.io.File
import java.lang.Exception

interface DfuCallback {

    fun onReady()

    /**
     * @param progress: 0f ~ 1f
     */
    fun onProgressChanged(progress: Float)

    fun onFailed(msg: String)

    fun onDone()

}

class DfuProcessCompat {

    private val scope = CoroutineScope(Dispatchers.Default)

    /**
     * @param device 当前连接设备的设备对象
     * @param advertisingMac 当前连接对象广播包中mac地址
     */
    fun update(
        context: Context,
        device: BluetoothDevice,
        zip: File,
        callback: DfuCallback
    ) {
        BluetoothCentral.releasePeripheral(context, device.address, disconnect = false)
        val dfuProcess = DfuProcess()
        scope.launch {
            val process = try {
                dfuProcess.initialize(context, device)
            } catch (e: Exception) {
                callback.onFailed(e.message ?: "Unknown Error")
                null
            }

            var success = true
            process?.apply {
                callback.onReady()
                delay(1000)
                update(zip)
                    .catch {
                        success = false
                        callback.onFailed(it.message ?: "Unknown Error")
                    }.collect {
                        callback.onProgressChanged(it)
                    }
            }
            if (success) {
                callback.onDone()
            }
        }
    }

}